<template>
  <div class="app-container" id="MqttDiv" style="padding: 0; margin: 0;">
    <div v-if="videoShow">
      <video :src="receiveMsg" style="object-fit: contain; width: 100%; height: 100%; border:0; margin:0; padding: 0;" :muted="true" loop :autoplay="true" controls></video>
      <div class="popup" @click="gotoLink(false)"></div>
    </div>
    <div v-else>
      <div @click="gotoLink(true)" style="color: #FFF;">返回</div>
      <!--<pdf 
        ref="pdf"
        :src="pdfUrl">
      </pdf>-->
    </div>
  </div>
</template>



<script setup>
// 在vue中如果想跟MQTT的服务端建立连接，只能使用websocket
import MqttUtils from "@/utils/MqttUtils"
// import pdf from 'vue-pdf'
console.log('MqttUtils:', MqttUtils);
// export default {
//   name: 'MqttView',
//   data() {
//     return {
const client = ref(null)  // MQTT客户端
const clientDisable = ref(false)  // MQTT客户端连接
const mqttSettingParams = ref({
  protocol: "ws",  // 协议
  host: "116.204.119.18",
  port: "8083", // 1883
  endpoint: "/mqtt",
  // endpoint: "",
  clientId: "vue2"+ Math.random().toString().substring(2,8),
  username: "ball",
  password: "ball@666888",
  keepalive: 30, // 心跳间隔(秒)
  connectTimeout: 4000, // 连接超时时间
  reconnectPeriod: 4000, // 重连间隔(毫秒)
  withCredentials: true,
})  // 配置信息
const settingRules = ref({
  protocol: [{ required: true, message: 'MQTT协议不能为空', trigger: 'blur' }],
  host: [{ required: true, message: '主机地址不能为空', trigger: 'blur' }],
  port: [{ required: true, message: '端口号不能为空', trigger: 'blur' }],
})

const subDisable = ref(false)  // 主题订阅
const subParams = ref({
  topic: "/a",
  qos: 0
})  // 订阅信息
const subRules = ref({
  topic: [{ required: true, message: '订阅主题不能为空', trigger: 'blur' }],
  qos: [{ required: true, message: 'Qos不能为空', trigger: 'blur' }],
})
const pubParams = ref({
  topic: "/a",
  payload: null,
  qos: 0
})  // 发布信息
const pubRules = ref({
  topic: [{ required: true, message: '订阅主题不能为空', trigger: 'blur' }],
  qos: [{ required: true, message: 'Qos不能为空', trigger: 'blur' }],
})

const receiveMsg = ref(null)  // 接收消息
const protocolOperation = ref([{label: "ws://", value: "ws"}, {label: "wss://", value: "wss"},{label: "mqtt://", value: "mqtt"}])  // MQTT协议字典
const qosOperation = ref([{label: "Qos 0", value: 0, detail: "最多一次"}, {label: "Qos 1", value: 1, detail: "至少一次"}, {label: "Qos 2", value: 2, detail: "仅一次"}])  // Qos字典
const videoShow = ref(true)
const pdfUrl = ref('./pdf/pdf.pdf')
    


    /**
     * 创建连接
     */
    const createConnection = () =>{
      // this.$refs["mqttSettingForm"].validate((valid) => {
      //   if (valid) {
          // console.log('this.mqttSettingParams:', this.mqttSettingParams);
          client.value = MqttUtils.createConnection(mqttSettingParams.value)
          if (!client.value) {
            clientDisable.value = false;
            // this.$message.error("客户端连接失败");
            return;
          }
          clientDisable.value = true;
          // this.$message.success("客户端连接成功");
          setTimeout(() => {
           subTopic();
          }, 3000);
      //   }
      // });
    }
    /**
     * 断开连接
     * 第一个参数：Boolean类型 false表示不会立马断开连接，给MQTT发送报文之后在关闭；true立马关闭连接，不会发送报文
     * 第二个参数：连接关闭之后的回调函数
     */
    const closeConnection = async () =>{
      const closeCoonection = await MqttUtils.closeConnection(client.value)
      if (closeCoonection) {
        clientDisable.value = false;
        // this.$message.success("客户端连接断开");
      } else {
        // this.$message.error("断开连接失败");
      }
    }
    /**
     * 订阅主题
     */
    const subTopic = async () =>{
      // this.$refs["subForm"].validate(async (valid) => {
      //   if (valid) {
          const subTopic = await MqttUtils.subTopic(client.value, subParams.value);
          // console.log(this.client, this.subParams);
          // console.log('subTopic:', subTopic);
          if (!subTopic) {
            // this.$message.error("主题订阅失败");
            return;
          }
          subDisable.value = true
          // this.$message.success("主题订阅成功");

          // 给连接对象注册一个接收消息的事件
          client.value.on("message", (topic, message) => {
            receiveMsg.value = message;
            // this.receiveMsg = topic + "--->" + message;
          });
      //   }
      // });
    }
    /**
     * 取消订阅
     */
    const closeSub = async () =>{
      const closeSub = await MqttUtils.closeSub(client.value, subParams.value);
      if (!closeSub) {
        // this.$message.error("取消订阅失败");
        return;
      }
      subDisable.value = false;
      // this.$message.success("取消订阅成功");
    }
    /**
     * 发布消息
     */
    // const pubMessage = async () =>{
    //   this.$refs["pubForm"].validate(async (valid) => {
    //     if (valid) {
    //       const pubMessage = await MqttUtils.pubMessage(client.value, pubParams.value);
    //       if (!pubMessage) {
    //         // this.$message.error("消息发送失败");
    //         return;
    //       }
    //       // this.$message.success("消息发送成功");
    //     }
    //   });

    // }
    const gotoLink = (status) =>{
      videoShow.value = status;
    }

    setTimeout(() => {
      createConnection();
    }, 3000);
//   }
// }
</script>
<style scoped>
#MqttDiv {
  width: 100%;
  height: 100vh;
  background: #000;
  overflow: hidden;
}
.popup{
  position: absolute;
  width: 100%;
  height: 100vh;
  background: rgba(0, 0, 0, 0);
  left: 0;
  top: 0;
  z-index: 990;
}

</style>